package org.example.huweb.web.sys_login.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.example.Result.StatusCode;
import org.example.entity.UserRole;
import org.example.exception.BusinessException;
import org.example.huweb.web.sys_login.mapper.UserRoleMappers;
import org.example.huweb.web.sys_login.service.UserRoleService;
import org.example.utils.JwtUtils;
import org.example.vo.UserReportVO;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMappers, UserRole> implements UserRoleService {
    //jwt工具类
    private final JwtUtils jwtUtils;

    //用户注册
    @Override
    public void adduser(UserRole userRole) {
        //判断账号是否存在
        List<UserRole> list = this.list(
                new LambdaQueryWrapper<UserRole>()
                        .eq(UserRole::getMyEmail, userRole.getMyEmail())
        );
        //如果存在，抛出异常
        if (!list.isEmpty()) {
            throw new BusinessException(StatusCode.ERROR_CODE, "账号已经存在");
        }
        //保存用户信息
        this.save(userRole);
    }

    //验证用户登录
    @Override
    public UserReportVO login(String email, String password) {
        // 根据邮箱和密码查询用户信息
        List<UserRole> list = this.list(
                new LambdaQueryWrapper<UserRole>()
                        .eq(UserRole::getMyEmail, email)
                        .eq(UserRole::getMyCipher, password)
        );

        // 如果查询不到，抛出异常
        if (list.isEmpty()) {
            throw new BusinessException(StatusCode.ERROR_CODE, "密码或账号错误");
        }

        // 如果查询到，将用户信息转换为UserReportVO并返回
        UserReportVO userReportVO = BeanUtil.copyProperties(list.get(0), UserReportVO.class);

        // 生成token
        userReportVO.setToken(
                jwtUtils.createJwt(
                        Map.of("uid", userReportVO.getUId())
                )
        );

        // 返回用户信息
        return userReportVO;
    }
}
